package com.yc;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;
@Configuration
@PropertySource("classpath:smtp.properties")

//邮件发送配置
public class SmtpConfig {

    @Value("${smtp.username}")
    private String username;
    @Value("${smtp.password}")
    private String password;
    @Value("${smtp.host}")
    private String host;
    @Value("${smtp.auth}")
    private String auth;
    @Value("${smtp.port}")
    private String port;
    @Value("${smtp.from}")
    private String from;


    @Bean
    public JavaMailSender   mailSender() {
        // 创建JavaMailSenderImpl对象，是JavaMailSender接口的实现
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
        javaMailSender.setHost(host);
        javaMailSender.setPort(Integer.parseInt(port));
        Properties p = javaMailSender.getJavaMailProperties();
        // 设置邮件发送的认证方式为开启
        p.put("mail.smtp.auth", auth);
        // 设置邮件传输协议为SMTP
        p.put("mail.transport.protocol", "smtp");
        // 设置支持的SSL协议版本
        p.put("mail.smtp.ssl.protocols", "TLSv1.2");
        // 根据端口号判断是否需要开启TLS
        if (port.equals("587")){
            p.put("mail.smtp.starttls.enable", "true");
        }
        // 根据端口号判断是否需要配置SSL
        if (port.equals("465")){
            p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            p.put("mail.smtp.socketFactory.port", "465");
            p.put("spring.mail.properties.mail.smtp.ssl.enable", "true");
        }
// 返回配置好的JavaMailSenderImpl对象，作为bean
        return javaMailSender;
    }


}
